/*
 * 1.登陆
 * 2.初始化会话队列
 * 3.获得当前会话
 * 3.初始化消息队列
 * 5.监听事件改变 有人发消息处理
 * 6.修改登陆人的profile
 * */
import genUserSig from '@/tim/GenerateTestUserSig'
import axios from '@/tim/ajax'
import {
  getCookie,
  getLoginUser,
  getNickName,
  getProjectId,
  jsonParseSafe,
  params2url,
  setCookie,
  throttle
} from '@/tim'

import myalert from '@/tim/myalert'
import { appointment_type_message, messageType_otherEnterMeeting, personage_system_group } from '@/tim/constact'

import {
  commit_set_currentMessageList,
  getCurrentMessageList,
  getNextReqMessageID,
  set_currentConversation
} from '@/store/message/MessageStoreUtil.js'
// import { uuid } from './index';
import { commit_set_currentConversation, getMessageState } from '@/store/message/MessageStoreUtil.js'
// import { MODE } from '../../match/config';
import { SDKAppID } from '@/settings.js'
import { type_src_supplier } from '@/tim/constact'
import Bus from '@/tim/bus.js'

export function initTIM () {
  const initTim = require('@/tim/tim')
  if (!window.tim) {
    const TIM = require('tim-js-sdk')
    window.tim = initTim.default()
    window.TIM = TIM
    if (window._vm) {
      window._vm.tim = window.tim
      window._vm.TIM = TIM
    }
  }
  return Promise.resolve()
}

export async function importUserToIm (userId, userSig) {
  return axios.get(`https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=${SDKAppID}&identifier=honey&usersig=${userId}&random=${userId}&contenttype=json`)``
}

/*
* @desc
* 展商获取展商的id
* 观众直接获取id
*
* */
export function getUserId () {
  var user = getLoginUser()
  if (user) {
    return user.platformUserId + ''
  }
  return ''
}

export async function loginIM (userId) {
  var userId_ = userId
  var userSig = await genUserSig(userId_)
  // 导入用户在登录
  // await importUserToIm(userId, userSig)
  // * 1.登陆
  // await window.tim.logout();
  console.log(userId_, userSig)
  return window.tim.login({
    userID: userId_,
    userSig
  })
    .then(res => {
      // 登录之后 cookie标记
      setCookie('isImLogin', true)
      console.log('用户登录', userId_)
      // 跟新一下用户id
      // updateProfile(getLoginUser())
    })
    .catch(e => {
      console.error('== window.tim.login({======>', e)
    })
}
export async function logout () {
  // return userLogout().then(res => {
  if (window.tim.logout) {
    try {
      const res = await window.tim.logout()
      console.log("im退出成功")
    } catch (err) {
      console.log("im退出失败")
    }

  }

  // console.log(res)
  setCookie('user', '')
  sessionStorage.setItem('user', '')
  setCookie('isImLogin', '')
}
export function updateProfile (user_) {
  var user = user_ || getLoginUser()
  if (user && !user.platformUserId) return false
  return window.tim.updateMyProfile({
    nick: (user && user.name) || `游客` + window.uuid_,
    avatar: user && user.avatar,
    gender: window.TIM.TYPES.GENDER_MALE,
    selfSignature: '',
    allowType: window.TIM.TYPES.ALLOW_TYPE_ALLOW_ANY
  })
}

export function eventlist () {
  // 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
  window.tim.on(window.TIM.EVENT.SDK_READY, onSdkReady, this)
  // SDK内部出错
  window.tim.on(window.TIM.EVENT.ERROR, onError)
  // 收到新消息
  window.tim.on(window.TIM.EVENT.MESSAGE_RECEIVED, onReceiveMessage)
  //    KICKED_OUT
  //     window.tim.on(window._vm.TIM.EVENT.KICKED_OUT, KICKED_OUT)
  window.tim.on(
    window.TIM.EVENT.CONVERSATION_LIST_UPDATED,
    CONVERSATION_LIST_UPDATED
  )
}

function onError ({ data }) {
  if (data.message !== 'Network Error') {
    console.log('=====onError===>', data.message)
  }
}

function KICKED_OUT () {
  myalert.fail('您的账户其他人登录，您已经被踢下线,界面即将跳转...')
  setCookie('user', '')
  setTimeout(() => {
    location.reload()
  }, 1000)
}

function CONVERSATION_LIST_UPDATED ({ data }) {
  !window._vm || !window._vm.$store || window._vm.$store.commit('message/set_conversationList', data)
}

/*
 * 1.登陆
 * 2.初始化会话队列
 * 5.监听事件改变 有人发消息处理
 * 6.修改登陆人的profile
 * */
export async function onSdkReady () {
  console.log('========')
  console.log('onSdkReady')
  console.log('========')

  var user = getLoginUser()
  // 6修改个人标配资料
  await updateProfile(user)
  window._vm.$store.commit('message/set_isSdkReady', true)
  Bus.$emit('eventBeforeLoginIM') // 直播的监听先于登陆  loginIM
  // * 2.初始化会话队列
  await setCurrentConvasation() // 设置目前的聊天窗口
  var conversationList = await getConversationList()
  if (conversationList) {
    window._vm.$store.commit(
      'message/updateConversationList',
      conversationList
    )
  }
  messageBoxScrollToBottom() // 滚动到底部
}

// 个人系统信息组
async function createSystemGroup () {
  var user = getLoginUser()
  const result = await window.tim.getGroupList()
  var uuid = personage_system_group + user.id
  var groupList = result && result.data && result.data.groupList
  var _personage_system_groups = groupList.filter(item => item.groupID == uuid)
  var _personage_system_group = _personage_system_groups[0]
  // 如果不存在
  if (!_personage_system_group && user && user.id) {
    var imResponse = await window.tim.createGroup({
      name: personage_system_group,
      type: window.TIM.TYPES.GRP_CHATROOM,
      joinOption: window.TIM.TYPES.JOIN_OPTIONS_FREE_ACCESS,
      groupID: uuid,
      memberList: [{ userID: user && user.id }]
    })
    var group = imResponse.data.group
    _personage_system_group = group
    console.log('===createSystemGroup=====>', _personage_system_group)
  }
  console.log('==我的系统组======>', _personage_system_group)
  window._vm.$store.commit('message/set_systemGroup', _personage_system_group)
}

// 获取某个group的交流信息
export function getMessageListByGroupConversationId (
  groupConversationId,
  nextId
) {
}

export function createMessagePayload (data, description, extension) {
  return {
    data,
    description,
    extension
  }
}

export async function sendMessageToGroup (payload, groupId) {
  await window.tim.joinGroup({
    groupID: groupId,
    type: window.TIM.TYPES.GRP_CHATROOM
  })
  var message = await window.tim.createCustomMessage({
    to: groupId,
    conversationType: window.TIM.TYPES.CONV_GROUP,
    payload
  })
  return window.tim.sendMessage(message)
}

/*
*
* @第一次见面发送一条消息
* */
export async function sendMessage4First (toUserId) {
  var message = await window.tim.createTextMessage({
    to: toUserId,
    conversationType: window.TIM.TYPES.CONV_C2C,
    payload: {
      text: `hello`
    }
  })
  // this.pushCurrentMessageList(message)
  return window.tim.sendMessage(message).catch(e => {
    console.error('发送消息失败', e)
  })
}

async function getConversationList () {
  var a = await window.tim.getConversationList()
  // to:"undefined"
  // 过滤一些没有用的conversation
  var list = a && a.data && a.data.conversationList
  list = list.filter(item => item.to != 'undefined')
  return list
}

/*
 * 根据 conversation获取messageList*/
export async function getMessageListByConversation (conversation) {
  var currentConversation =
    (window._vm.$store.state.message &&
      window._vm.$store.state.message.currentConversation) || conversation
  if (!currentConversation) return false
  if (conversation.conversationID != currentConversation.conversationID) { return false } // 当信息会话不是选中的 就不需要刷新messageList
  if (conversation.conversationID != currentConversation.conversationID) {
    window._vm.$store.commit('message/set_currentMessageList', [])
  }

  if (conversation.conversationID == currentConversation.conversationID) {
    if (currentConversation.conversationID) {
      const prevConversationID = currentConversation.conversationID
      await window.tim.setMessageRead({ conversationID: prevConversationID })
    }
  }
  await window.tim.setMessageRead({
    conversationID: conversation.conversationID
  })
  window.tim
    .getConversationProfile(conversation.conversationID)
    .then(async ({ data }) => {
      // 更新 消息列表
      window._vm.$store.commit(
        'message/set_currentConversation',
        data.conversation
      )
      await window._vm.$store.dispatch(
        'message/getMessageList',
        data.conversation
      )
    })
  messageBoxScrollToBottom()
}

function getVideoDetailMessage () {
  var url = '/user/yiwu/videoCall/detail'
  if (MODE == '闻信') {
    url = '/videoCall/detail'
  }
  return url
}

/* 收到消息处理
 * 1.payload.data==='remove_metting' //退出会议
 * 2.payload.text  //普通的收到信息 alert 前端提示
 * 3.payload.data==='video'  //视频会话
 * 4.payload.data==='sound'  //虚拟电话
 * */
const onReceiveMessage = throttle(async ({ data: messageList }) => {
  console.log('==onReceiveMessage======>', messageList)
  // 在管理界面停止提示框
  var messageOne = messageList[0]
  var payloadData = jsonParseSafe(messageOne.payload.data)
  if (messageOne.from == getUserId()) return false // 自己就不提示
  if (messageOne.to.indexOf('group_zhibo') >= 0) {
    // 说明是直播 不需要提醒
    return false
  }
  // 如果是视频邀请
  if (messageOne.payload.extension == appointment_type_message.videoCall || messageOne.payload.extension == appointment_type_message.wxVideoCall) {
    // 不会关闭 除非手动取消
    var url = `${getVideoDetailMessage()}?${params2url({
      roomId: payloadData.roomID,
      projectId: getProjectId()
    })}`
    console.log(url)
    window._vm.$notify({
      title: window._vm.$t('lang.视频邀约') + ' ' + payloadData.fromnick,
      dangerouslyUseHTMLString: true,
      message: `<a href="${url}"  target="_blank">${window._vm.$t('lang.点击查看')}</a> `,
      duration: 0,
      position: 'bottom-right'
    })
    return false
  }
  //  extension: 'videoCallInvite' 来之小程序的 视频邀请
  var payload = jsonParseSafe(messageOne.payload.data)
  if (payload && payload.type == 'TRTC_EVENT_MEETING_INVITE') {
    // 不会关闭 除非手动取消
    var payloadData = jsonParseSafe(messageOne.payload.data)
    var url = `${getVideoDetailMessage()}?${params2url({
      roomId: payloadData.roomID,
      projectId: getProjectId()
    })}`
    console.log(url)
    window._vm.$notify({
      title: window._vm.$t('lang.视频邀约') + ' ' + payload.fromnick,
      dangerouslyUseHTMLString: true,
      message: `<a href="${url}"  target="_blank">${window._vm.$t('lang.点击查看')}</a> `,
      duration: 0,
      position: 'bottom-right'
    })
    return false
  }
  // 提示邀约邀请
  if (messageOne.payload.extension == appointment_type_message.remind) {
    // 不会关闭 除非手动取消
    window._vm.$notify({
      title: '邀约提醒',
      dangerouslyUseHTMLString: true,
      message: `<a href="${messageOne.payload.data}"   target="_blank">点击查看</a> `,
      duration: 0
    })
    return false
  }

  // 发起邀约邀请
  if (messageOne.payload.extension == appointment_type_message.invite) {
    window._vm.$notify({
      title: messageOne.payload.description,
      dangerouslyUseHTMLString: true,
      message: `<a href="${messageOne.payload.data}"   target="_blank">点击查看</a> `,
      duration: 0
    })
    return false
  } // otherEnterMeeting 贸易配对活动
  if (messageOne.payload.extension == messageType_otherEnterMeeting) {
    // 不会关闭 除非手动取消
    window._vm
      .$confirm(window._vm.$t('lang.您有一个会议正在进行中'), window._vm.$t('lang.提示'), {
        confirmButtonText: window._vm.$t('lang.进入'),
        cancelButtonText: window._vm.$t('lang.取消'),
        type: 'warning',
        showClose: false,
        closeOnClickModal: false
      })
      .then(res => {
        push(messageOne.payload.data)
        return true
      })
      .catch(e => {
        location.reload()
        return false
      })
    return false
  }
  if (messageOne.payload.text || messageOne.payload.data || messageOne.payload.uuid) {
    var result, userNickName, message
    if (messageOne.payload.text) {
      result = messageOne.payload.text.split(`··`)
      userNickName = result[0] || ''
      message = result[1] || ''
    }
    if (messageOne.payload.data) {
      userNickName = messageOne.nick || ''
      message = messageOne.payload.data
    }
    if (messageOne.payload.uuid) {
      userNickName = messageOne.nick || ''
      message = '图片'
    }

    // 如果当前打开的页面是 //message 而且接受的信息就是当前的对话框
    if (
      window._vm.$route.fullPath.indexOf('/tim/im') >=
      0
    ) {
      var conversationID = messageOne.conversationID
      var currentConversation =
        window._vm.$store.state.message &&
        window._vm.$store.state.message.currentConversation
      if (!currentConversation) return false
      if (conversationID != currentConversation.conversationID) return false // 当信息会话不是选中的 就不需要刷新messageList
      window._vm.$store.state.message.currentMessageList = [
        ...window._vm.$store.state.message.currentMessageList,
        ...messageList
      ]
      window._vm.$store.commit(
        'message/set_currentMessageList',
        window._vm.$store.state.message.currentMessageList
      )
      window.tim.setMessageRead({
        conversationID: currentConversation.conversationID
      })
      messageBoxScrollToBottom()
    }
    // 如果已经再消息界面 就不刷新了
    if (window._vm.$route.fullPath.indexOf('/tim/im') >= 0) {
      return false
    }
    var messagePathUrl = getMessageUrl()
    window._vm.$notify({
      dangerouslyUseHTMLString: true,
      message: `<a href="${messagePathUrl}">${message}</a> `,
      title: `${'收到来自' + userNickName + '的消息'}`
      // message: `${message}`
    })
    return false
  }
}, 1000)

export function messageBoxScrollToBottom () {
  var dom = $('.myScrollbar .el-scrollbar__wrap')[0]
  dom && dom.scrollHeight && $(dom).animate && $(dom).animate({ scrollTop: dom.scrollHeight + 200 }, 500)

  var dom_ = $('.myScrollbar')[0]
  dom_ && dom_.scrollHeight && $(dom_).animate && $(dom_).animate({ scrollTop: dom_.scrollHeight + 200 }, 500)
}

/*
     加好友
     create对话
     * 对话的消息array*/
export function createConversation ({ from, to }) {
  // 当前对话就是这个 什么都不处理
  var conversationID = `C2C${to}`
  if (
    window._vm.$store.state.message.currentConversation.conversationID ==
    conversationID
  ) {
    return Promise.resolve(true)
  }

  // 1.切换会话前，将切换前的会话进行已读上报
  if (window._vm.$store.state.message.currentConversation.conversationID) {
    const prevConversationID =
      window._vm.$store.state.message.currentConversation.conversationID
    window.tim.setMessageRead({ conversationID: prevConversationID })
  }
  // 2.待切换的会话也进行已读上报
  window.tim.setMessageRead({ conversationID })
  // clear 对话信息
  window._vm.$store.commit('message/set_currentMessageList', [])
  return (
    window.tim &&
    window.tim.getConversationProfile &&
    window.tim.getConversationProfile(conversationID).then(({ data }) => {
      // 跟新 会话列表
      // 3.1 更新当前会话
      window._vm.$store.commit(
        'message/set_currentConversation',
        data.conversation
      )
      // 3.2 获取消息列表
      window._vm.$store.dispatch('message/getMessageList', data.conversation)
      return data.conversation || true
    })
  )
}

export async function setCurrentConvasation () {
  var cache_conversation_conversationID = getCookie(
    'cache_conversation_conversationID'
  )
  if (!cache_conversation_conversationID) return Promise.resolve(false)
  return await window._vm.$store.dispatch(
    'message/action_checkoutConversation',
    {
      conversationID: cache_conversation_conversationID
    }
  )
}

// 删除 会话
export function deleteConversation (id) {
  window.tim.deleteConversation(id)
}

// 会话的每个人的具体信息头像
export async function getProfile4Conversation () {
  var conversationList = window._vm.$store.state.message.conversationList
  var userIds = conversationList.map(user => {
    return user.userProfile.userID
  })
  const resulkts = await window.tim.getUserProfile({
    userIDList: userIds // 请注意：即使只拉取一个用户的资料，也需要用数组类型，例如：userIDList: ['user1']
  })
  // window._vm.$store.commit('message/updateConversationList', conversationList)
}

// 提醒对方预约
export async function sendCustomMessage_remindOther (to, { data }) {
  var message = await window.tim.createCustomMessage({
    to: to,
    conversationType: window.TIM.TYPES.CONV_C2C,
    payload: {
      data: data, // 用于标识该消息是骰子类型消息
      description: '提醒对方预约',
      extension: 'remindOther'
    }
  })
  return window.tim.sendMessage(message)
}

// 提醒对方进入会议
/*
 * to 是通知对方的id
 * data 会议进入路径
 * */
export async function sendCustomMessage_otherEnterMeeting (to, { data }) {
  var message = await window.tim.createCustomMessage({
    to: to,
    conversationType: window.TIM.TYPES.CONV_C2C,
    payload: {
      data: data,
      description: '提醒对方预约',
      extension: 'otherEnterMeeting'
    }
  })
  return window.tim.sendMessage(message)
}

/* 小程序
 * 发送视频消息*/
export function createVideoWxPayload (fromnick, fromuserid, roomid) {
  return {
    type: 'TRTC_EVENT_MEETING_INVITE',
    roomId: roomid,
    roomID: roomid,
    debugMode: false,
    cloudenv: 'PRO',
    template: '1V1',
    fromNick: fromnick,
    fromID: fromuserid,
    fromnick,
    fromuserid
  }
}

export async function sendVideoCall2wx (to, data) {
  var message = await window.tim.createCustomMessage({
    to: to,
    conversationType: window.TIM.TYPES.CONV_C2C,
    payload: {
      data: JSON.stringify(data),
      description: window._vm.$t('lang.视频邀约') + ' ' + data.fromnick,
      extension: 'videoCallInvite'
    }
  })
  return window.tim.sendMessage(message)
}

export async function sendMessage (to, data) {
  var message = await window.tim.createCustomMessage({
    to: to,
    conversationType: window.TIM.TYPES.CONV_C2C,
    payload: {
      data: data.url,
      description: data.description,
      extension: data.extension
    }
  })
  return window.tim.sendMessage(message)
}

/*
* 1 设置currentConversation
* 2. 获取信息
* */
export async function getFirstMessageListByConversation (conversation) {
  set_currentConversation(conversation)
  var conversationID = conversation.conversationID
  window.tim.setMessageRead({ conversationID })
  window.tim.getMessageList({
    conversationID,
    nextReqMessageID: getNextReqMessageID(),
    count: 15
  }).then(imReponse => {
    var currentMessageList_ = getCurrentMessageList()
    var nextReqMessageID = imReponse.data.nextReqMessageID
    var isCompleted = imReponse.data.isCompleted
    var currentMessageList = [...imReponse.data.messageList, ...currentMessageList_]
    commit_set_currentMessageList(currentMessageList)
  })
}

export async function getMessageListMore (nextConversationId) {
  window.tim.setMessageRead({ conversationID: nextConversationId })
  window.tim.getMessageList({
    conversationID: nextConversationId,
    count: 15
  }).then(imReponse => {
    var currentMessageList_ = getCurrentMessageList()
    var nextReqMessageID = imReponse.data.nextReqMessageID
    var isCompleted = imReponse.data.isCompleted
    var currentMessageList = [...imReponse.data.messageList, ...currentMessageList_]
    commit_set_currentMessageList(currentMessageList)
  })
}

export async function triggerSendMessageOther (userId) {
  /*
  加好友
  * create 对话
  * 对话的消息array
  * 跳转界面*/
  var currentUser = getLoginUser()
  var isExhibitor_ = currentUser == type_src_supplier
  // 如果是展商
  if (isExhibitor_) {
    if (currentUser.contactId == userId) {
      myalert.fail(window._vm.$t('lang.不能给自己发消息'))
      return false
    }
    if (currentUser.contactId == null || currentUser.contactId == undefined || currentUser.contactId == '') {
      this.loginVisible = !this.loginVisible
      return false
    }
  } else {
    if (currentUser.id == userId) {
      myalert.fail(window._vm.$t('lang.不能给自己发消息'))
      return false
    }
    if (currentUser.id == null || currentUser.id == undefined || currentUser.id == '') {
      this.loginVisible = !this.loginVisible
      return false
    }
  }

  var result = await createConversation({
    from: currentUser.contactId || currentUser.id,
    to: userId
  }).catch(e => {
    myalert.fail('对方还未登录系统，暂时不能联系')
    return false
  })
  if (!result) return false
  /* 选择当前的对话和对话信息*/
  if (window._vm.$store.state.message && window._vm.$store.state.message.currentConversation &&
    window._vm.$store.state.message.currentConversation.conversationID) {
    setCookie('cache_conversation_conversationID', window._vm.$store.state.message.currentConversation.conversationID)
  }
  var url = ''
  url = '/admin-web/#/tim/im'
  url = `${url}?${params2url({
    from: currentUser.contactId,
    to: userId,
  })}`
  window.open(url)
}

export function getMessageUrl () {
  var url = ''
  url = '/admin-web/#/tim/im'
  return url
}

export function currentConversation () {
  return getMessageState().currentConversation
}

export function selectConversation (conversation) {
  commit_set_currentConversation(conversation)
  return getFirstMessageListByConversation(conversation)
}

